/*
 *                    BioJava development code
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  If you do not have a copy,
 * see:
 *
 *      http://www.gnu.org/copyleft/lesser.html
 *
 * Copyright for this code is held jointly by the individual
 * authors.  These should be listed in @author doc comments.
 *
 * For more information on the BioJava project and its aims,
 * or to join the biojava-l mailing list, visit the home page
 * at:
 *
 *      http://www.biojava.org/
 *
 * Created on 15.08.2007
 * @author Asia Grzibovska
 *
 */

package uk.ac.sanger;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.net.*;

import java.util.*;               // Hashtable, lists, and so on

public class DataManager implements DataManagerInterface{

	public static String new_system_name;

	DatabaseUtilities dao;

	DataSource dataSource=null;

	public DataManager(){
		dao = new DatabaseUtilities();
		try {
			Context env = (Context) new InitialContext().lookup("java:comp/env");
			dataSource = (DataSource) env.lookup("jdbc/ag7_test");
		}
		catch (Exception e){
			e.printStackTrace();
			System.err.println("could not initialize dataSource, something is seriously broken.");
		}	
		
	}


	public int getIdFromUri(String uri){
		int id = -1;
	
		Connection conn = null;
		try {
			
			if (dataSource!=null){
				try{
					conn = dataSource.getConnection();
				} catch (Exception e){
					e.printStackTrace();
				}
				if(conn!=null){
					id=dao.getIdFromUri(conn, uri);
					new_system_name=dao.getSystemName();}	
			}
			
		} catch (Exception e){
			e.printStackTrace();
		}
		
		if ( conn != null){
			try {
				conn.close();
			} catch (SQLException ex){
				ex.printStackTrace();
			}
		}
		
		return id;
	}

	public String saveFeature(FeatureBean[] features, 
			                  String coordinateSystemURI)
	{
        //return OK if success, otherwise error message
		String reply="";
		Connection conn = null;
		int id = getIdFromUri(coordinateSystemURI);
		
		try {
			if( id > 0 ){
				conn = dataSource.getConnection();
				if (conn!=null)
					reply= dao.saveFeature(conn, features,id).toString();	
				else reply="Error! No database connection!";
			}
			else reply = "Error! Coordinate system URI incorrect!"+id;

		} 	
		catch (SQLException e){
			reply="Error!!! "+e.getMessage();
			e.printStackTrace();
		}		
		catch (Exception e){
			reply="Error!!! "+e.getMessage();
			e.printStackTrace();
		}

		if ( conn != null){
			try {
				conn.close();
			} catch (SQLException ex){
				reply="Error!!! "+ex.getMessage();
				ex.printStackTrace();
			}
		}
		return reply;
	}

	public String updateFeature(FeatureBean[] features, 
			                    String coordinateSystemURI)
	{	
	    //return OK if success, otherwise error message
		String reply="";
		Connection conn = null;

		int id = getIdFromUri(coordinateSystemURI);

		try {
			if ( id > 0 ){

				conn = dataSource.getConnection();

				reply=dao.updateFeature(conn, features, id);
			}
			else reply = "Error! Coordinate system URI incorrect!";

		} catch (SQLException e){
			reply="Error!!! "+e.getMessage();
			e.printStackTrace();
		}

		if ( conn != null){
			try {
				conn.close();
			} catch (SQLException ex){
				reply="Error!!! "+ex.getMessage();
				ex.printStackTrace();
			}
		}
		return reply;
	}

	public String deleteFeature(FeatureBean[] features, 
			                    String coordinateSystemURI)
	{
		//return OK if success, otherwise error message
		String reply="";		
		Connection conn = null;
		int id = getIdFromUri(coordinateSystemURI);

		try {
			if ( id > 0 ){
				conn = dataSource.getConnection();

				reply=dao.deleteFeature(conn, features, id);
			}
			else reply = "Error! Coordinate system URI incorrect!";

		} catch (SQLException e){
			e.printStackTrace();
			reply="Error!!! "+e.getMessage();
		}

		if ( conn != null){
			try {
				conn.close();
			} catch (SQLException ex){
				ex.printStackTrace();
				reply="Error!!! "+ex.getMessage();
			}
		}
		return reply;
	}

	public boolean saveHistory(FeatureBean features, 
			String action, 
			String commit_msg, 
			String coordinateSystemURI,
			String user)
	{
		int id = getIdFromUri(coordinateSystemURI);
		boolean ok=false;
		Connection conn = null;

		try {
			if ( id > 0){
				conn = dataSource.getConnection();

				ok = dao.saveHistory(conn, features, action, 
						commit_msg, id, user);
			}
			else ok=false;

		} catch (SQLException e){
			e.printStackTrace();
			return false;
		}

		if ( conn != null){
			try {
				conn.close();
			} catch (SQLException ex){
				ex.printStackTrace();
				return false;
			}
		}
		return ok;
	}

	public FeatureBean[] getAllFeatures(String coordinateSystemURI){
		FeatureBean[] features = null;

		int id = getIdFromUri(coordinateSystemURI);

		Connection conn = null;

		try {
			if ( id > 0 ){
				conn = dataSource.getConnection();

				features = dao.getAllFeatures(conn,id);
			}
		} catch (SQLException e){
			e.printStackTrace();

		}

		if ( conn != null){
			try {
				conn.close();
			} catch (SQLException ex){
				ex.printStackTrace();
			}
		}
		return features;
	}

	public FeatureBean getFeatureById(String feature_id,
			                          String coordinateSystemURI){

		FeatureBean bean = null;
		Connection conn = null;	

		int id = getIdFromUri(coordinateSystemURI);

		try {
			if ( id > 0 ){
				conn = dataSource.getConnection();
				bean = dao.getFeatureById(conn, feature_id, id);
			}
		} catch (SQLException e){
			e.printStackTrace();

		}

		if ( conn != null){
			try {
				conn.close();
			} catch (SQLException ex){
				ex.printStackTrace();
			}
		}
		return bean;
	}

	public FeatureBean[] getHistoryById(String feature_id,
			                            String coordinateSystemURI){

		FeatureBean[] features = null;

		int id = getIdFromUri(coordinateSystemURI);
		
		Connection conn = null;

		try {
			if ( id > 0 ){
				conn = dataSource.getConnection();

				features = dao.getHistoryById(conn,feature_id,id);
			}
		} catch (SQLException e){
			e.printStackTrace();
		}

		if ( conn != null){
			try {
				conn.close();
			} catch (SQLException ex){
				ex.printStackTrace();
			}
		}
		return features;
	}

	public List getGroups(String coordinateSystemURI){

		List groups = null;

		int id = getIdFromUri(coordinateSystemURI);

		Connection conn = null;

		try {
			if ( id > 0 ){
				conn = dataSource.getConnection();

				groups = dao.getGroups(conn,id);
			}
		} catch (SQLException e){
			e.printStackTrace();
		}

		if ( conn != null){
			try {
				conn.close();
			} catch (SQLException ex){
				ex.printStackTrace();
			}
		}
		return groups;
	}

	public void saveCoordinate( String[][] coordinates){

		Connection conn = null;

		try {

			conn = dataSource.getConnection();

			dao.saveCoordinate( conn, coordinates);

		} catch (SQLException e){
			e.printStackTrace();
		}

		if ( conn != null){
			try {
				conn.close();
			} catch (SQLException ex){
				ex.printStackTrace();
			}
		}
	}

	public void saveGroups( List groups,String coordinateSystemURI){

		int id = getIdFromUri(coordinateSystemURI);

		Connection conn = null;

		try {
			if( id > 0 ){
				conn = dataSource.getConnection();

				dao.saveGroups( conn, groups,id);
			}
		} catch (SQLException e){
			e.printStackTrace();
		}

		if ( conn != null){
			try {
				conn.close();
			} catch (SQLException ex){
				ex.printStackTrace();
			}
		}
	}
	
	public void deleteGroup( String group,
			                 String coordinateSystemURI){

		int id = getIdFromUri(coordinateSystemURI);

		Connection conn = null;

		try {
			if( id > 0 ){
				conn = dataSource.getConnection();

				dao.deleteGroup( conn, group, id);
			}
		} catch (SQLException e){
			e.printStackTrace();
		}

		if ( conn != null){
			try {
				conn.close();
			} catch (SQLException ex){
				ex.printStackTrace();
			}
		}
	}
	
	public String getAttributeById(String groupid,
			String coordinateSystemURI){

		Connection conn = null;	

		int id = getIdFromUri(coordinateSystemURI);

		String attribute="";
		
		try {
			if ( id > 0 ){
				conn = dataSource.getConnection();
				attribute = dao.getAttributeById(conn, groupid, id);
			}
		} catch (SQLException e){
			e.printStackTrace();

		}

		if ( conn != null){
			try {
				conn.close();
			} catch (SQLException ex){
				ex.printStackTrace();
			}
		}
		return attribute;
	}
	
	public FeatureBean[] getFeaturesByGroup(String groupid,
										 String coordinateSystemURI){

		FeatureBean[] features = null;
		Connection conn = null;	

		int id = getIdFromUri(coordinateSystemURI);

		try {
			if ( id > 0 ){
				conn = dataSource.getConnection();
				features = dao.getFeaturesByGroup(conn, groupid, id);
			}
		} catch (SQLException e){
			e.printStackTrace();

		}

		if ( conn != null){
			try {
				conn.close();
			} catch (SQLException ex){
				ex.printStackTrace();
			}
		}
		return features;
	}

	
}
